/*
 * @Author: ylq
 * @Date: 2022-09-20 16:05:55
 * @Desc: 路由基本规则
 * @Last Modified by: ylq
 * @Last Modified time: 2023-09-18 15:26:00
 */
import { isLogin } from '@/utils/auth';
import { useUserStore } from '@/store';
import usePermission from '@/hooks/permission';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
// import { appRoutes } from '../routes';
function setupGuard(router) {
  // 路由守卫
  router.beforeEach(async (to, from, next) => {
    document.title = to.meta?.title ? to.meta.title : '烽火Media';
    const loginPath = {
      name: 'login',
      query: {
        redirect: to.path,
        ...to.query
      }
    };
    NProgress.start();
    const userStore = useUserStore();
    // 要排查的等级，从后往前排
    const level = 0;
    // if(to.matched[0]?.meta?.single){
    //   level = 0;
    // }

    async function checkRouter() {
      const Permission = usePermission();
      console.log(30, Permission.accessRouter(to), to, userStore?.userInfo?.roles);
      if (Permission.accessRouter(to)) await next();
      else {
        let destination = undefined;
        // 逐级往上级找可用。
        for (let index = to.matched.length - 1; index >= 0; index--) {
          const ele = to.matched[index];

          if (destination) break;
          if (index === level) {
            destination = Permission.findFirstPermissionRoute(ele?.children, userStore?.userInfo?.roles);

            break;
          }
          if (index >= level && !destination) {
            destination = Permission.findFirstPermissionRoute(ele?.children, userStore?.userInfo?.roles);
          }
        }
        // 如果上面都没有，那就返回404
        if (!destination) {
          destination = {
            name: 'notFound',
            query: { ...to.query, path: to.path }
          };
        }
        // const m = to.matched[to.matched.length - 2];// m?.children,
        // const single = to.matched[0]?.meta?.single;
        // const destination = Permission.findFirstPermissionRoute((single && to.matched[1]?.children) || m?.children || appRoutes, userStore?.userInfo?.roles) || ;

        await next(destination);
      }
      NProgress.done();
    }
    // 检查用户是否已登录
    if (isLogin()) {
      if (userStore.userInfo) {
        checkRouter();
      } else {
        try {
          await userStore.getUserinfo();

          checkRouter();
        } catch (error) {
          next(loginPath);
        }
      }
      NProgress.done();
    } else {
      // 避免无限重定向
      if (to.name === 'login') {
        next();
        NProgress.done();
        return;
      }
      // 将用户重定向到登录页面
      next(loginPath);
      NProgress.done();
    }
  });

  router.beforeResolve(async (to) => {
    console.log(to, '解析');
  });
}
export default function routeGuard(router) {
  console.log(router);
  setupGuard(router);
}
